package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.LogisticsConfigRepository;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.Objects;

@Service

public class LogisticsConfigService {
    @Autowired
    private LogisticsConfigRepository logisticsConfigRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<LogisticsConfig> pageLogisticsConfig(Long userId,Integer freeFreight,int pageNum, int pageSize) {
        QLogisticsConfig qLogisticsConfig = QLogisticsConfig.logisticsConfig;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(userId)){
            builder.and(qLogisticsConfig.userId.eq(userId));
        }
        if (!Objects.isNull(freeFreight)){
            builder.and(qLogisticsConfig.freeFreight.eq(freeFreight));
        }
        return queryFactory.select(
                        Projections.bean(
                                LogisticsConfig.class,
                                qLogisticsConfig.freeFreight,
                                qLogisticsConfig.userId,
                                qLogisticsConfig.freightFee,
                                qLogisticsConfig.id
                        )
                ).from(qLogisticsConfig)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    public Result saveModel(Long userId, Integer freeFreight, BigDecimal freightFee, String remark) {
        LogisticsConfig logisticsConfig = new LogisticsConfig();
        logisticsConfig.setId(Snowflake.generateId());
        logisticsConfig.setFreeFreight(freeFreight);
        logisticsConfig.setUserId(userId);
        logisticsConfig.setFreightFee(freightFee);
        logisticsConfigRepository.save(logisticsConfig);
        return Result.ok();
    }

    public Result delete(Long logisticsConfigId) {
        logisticsConfigRepository.deleteById(logisticsConfigId);
        return Result.ok();
    }

    public Result findById(Long logisticsConfigId) {
        return Result.ok(logisticsConfigRepository.findById(logisticsConfigId).get());
    }
}
